<template>
  <div class="statistics-container">
    <!-- 时间范围选择 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-cascader
            v-model="filterForm.categoryIds"
            :options="categoryOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择商品分类"
            clearable
            @change="handleCategoryChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据概览 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总销售额</span>
              <el-tooltip content="统计时间范围内的商品销售总额" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ formatNumber(overview.totalSales) }}</div>
            <div class="trend">
              <span :class="['trend-value', overview.salesTrend >= 0 ? 'up' : 'down']">
                {{ overview.salesTrend >= 0 ? '+' : '' }}{{ overview.salesTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单数</span>
              <el-tooltip content="统计时间范围内的订单总数" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ formatNumber(overview.orderCount) }}</div>
            <div class="trend">
              <span :class="['trend-value', overview.orderTrend >= 0 ? 'up' : 'down']">
                {{ overview.orderTrend >= 0 ? '+' : '' }}{{ overview.orderTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>商品数</span>
              <el-tooltip content="当前在售商品总数" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ formatNumber(overview.goodsCount) }}</div>
            <div class="trend">
              <span :class="['trend-value', overview.goodsTrend >= 0 ? 'up' : 'down']">
                {{ overview.goodsTrend >= 0 ? '+' : '' }}{{ overview.goodsTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="data-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>转化率</span>
              <el-tooltip content="商品浏览量转化为订单的比例" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ overview.conversionRate }}%</div>
            <div class="trend">
              <span :class="['trend-value', overview.conversionTrend >= 0 ? 'up' : 'down']">
                {{ overview.conversionTrend >= 0 ? '+' : '' }}{{ overview.conversionTrend }}%
              </span>
              <span class="trend-label">较上期</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-radio-group v-model="salesChartType" size="small">
                <el-radio-button label="day">日</el-radio-button>
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="salesChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品分类占比</span>
            </div>
          </template>
          <div class="chart-container" ref="categoryChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品排行 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>热销商品排行</span>
              <el-radio-group v-model="hotGoodsType" size="small">
                <el-radio-button label="sales">销售额</el-radio-button>
                <el-radio-button label="count">销量</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <el-table :data="hotGoodsList" style="width: 100%">
            <el-table-column type="index" label="排名" width="80" />
            <el-table-column label="商品信息" min-width="300">
              <template #default="{ row }">
                <div class="goods-info">
                  <el-image :src="row.image" class="goods-image" />
                  <div class="goods-detail">
                    <div class="goods-name">{{ row.name }}</div>
                    <div class="goods-category">{{ row.categoryName }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sales" label="销售额" width="120">
              <template #default="{ row }">
                ¥{{ formatNumber(row.sales) }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="销量" width="120" />
            <el-table-column prop="trend" label="趋势" width="120">
              <template #default="{ row }">
                <span :class="['trend-value', row.trend >= 0 ? 'up' : 'down']">
                  {{ row.trend >= 0 ? '+' : '' }}{{ row.trend }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>商品评价分析</span>
            </div>
          </template>
          <div class="review-analysis">
            <div class="review-overview">
              <div class="review-score">
                <div class="score">{{ reviewAnalysis.score }}</div>
                <div class="score-label">综合评分</div>
                <el-rate
                  v-model="reviewAnalysis.score"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </div>
              <div class="review-tags">
                <el-tag
                  v-for="tag in reviewAnalysis.tags"
                  :key="tag.name"
                  :type="tag.type"
                  class="review-tag"
                >
                  {{ tag.name }} ({{ tag.count }})
                </el-tag>
              </div>
            </div>
            <div class="review-trend">
              <div class="trend-title">评分趋势</div>
              <div class="chart-container" ref="reviewChartRef"></div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getGoodsStatistics,
  getGoodsCategories,
  getGoodsSalesTrend,
  getGoodsCategoryRatio,
  getHotGoodsList,
  getGoodsReviewAnalysis
} from '@/api/goods'

// 图表实例
let salesChart = null
let categoryChart = null
let reviewChart = null

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  categoryIds: []
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 分类选项
const categoryOptions = ref([])

// 数据概览
const overview = reactive({
  totalSales: 0,
  salesTrend: 0,
  orderCount: 0,
  orderTrend: 0,
  goodsCount: 0,
  goodsTrend: 0,
  conversionRate: 0,
  conversionTrend: 0
})

// 图表类型
const salesChartType = ref('day')
const hotGoodsType = ref('sales')

// 热销商品列表
const hotGoodsList = ref([])

// 评价分析
const reviewAnalysis = reactive({
  score: 0,
  tags: [],
  trend: []
})

// 图表容器引用
const salesChartRef = ref(null)
const categoryChartRef = ref(null)
const reviewChartRef = ref(null)

// 获取分类列表
const fetchCategories = async () => {
  try {
    const { data } = await getGoodsCategories()
    categoryOptions.value = data
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const { data } = await getGoodsStatistics({
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      categoryIds: filterForm.categoryIds
    })
    Object.assign(overview, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取销售趋势
const fetchSalesTrend = async () => {
  try {
    const { data } = await getGoodsSalesTrend({
      type: salesChartType.value,
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      categoryIds: filterForm.categoryIds
    })
    updateSalesChart(data)
  } catch (error) {
    console.error('获取销售趋势失败:', error)
    ElMessage.error('获取销售趋势失败')
  }
}

// 获取分类占比
const fetchCategoryRatio = async () => {
  try {
    const { data } = await getGoodsCategoryRatio({
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1]
    })
    updateCategoryChart(data)
  } catch (error) {
    console.error('获取分类占比失败:', error)
    ElMessage.error('获取分类占比失败')
  }
}

// 获取热销商品
const fetchHotGoods = async () => {
  try {
    const { data } = await getHotGoodsList({
      type: hotGoodsType.value,
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      categoryIds: filterForm.categoryIds
    })
    hotGoodsList.value = data
  } catch (error) {
    console.error('获取热销商品失败:', error)
    ElMessage.error('获取热销商品失败')
  }
}

// 获取评价分析
const fetchReviewAnalysis = async () => {
  try {
    const { data } = await getGoodsReviewAnalysis({
      startDate: filterForm.dateRange[0],
      endDate: filterForm.dateRange[1],
      categoryIds: filterForm.categoryIds
    })
    Object.assign(reviewAnalysis, data)
    updateReviewChart(data.trend)
  } catch (error) {
    console.error('获取评价分析失败:', error)
    ElMessage.error('获取评价分析失败')
  }
}

// 更新销售趋势图表
const updateSalesChart = (data) => {
  if (!salesChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['销售额', '订单数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'bar',
        data: data.sales
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        data: data.orders
      }
    ]
  }
  
  salesChart.setOption(option)
}

// 更新分类占比图表
const updateCategoryChart = (data) => {
  if (!categoryChart) return
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      type: 'scroll'
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  
  categoryChart.setOption(option)
}

// 更新评价趋势图表
const updateReviewChart = (data) => {
  if (!reviewChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 5
    },
    series: [
      {
        type: 'line',
        smooth: true,
        data: data.scores,
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        }
      }
    ]
  }
  
  reviewChart.setOption(option)
}

// 初始化图表
const initCharts = () => {
  salesChart = echarts.init(salesChartRef.value)
  categoryChart = echarts.init(categoryChartRef.value)
  reviewChart = echarts.init(reviewChartRef.value)
  
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  salesChart?.resize()
  categoryChart?.resize()
  reviewChart?.resize()
}

// 搜索
const handleSearch = () => {
  fetchStatistics()
  fetchSalesTrend()
  fetchCategoryRatio()
  fetchHotGoods()
  fetchReviewAnalysis()
}

// 重置
const handleReset = () => {
  filterForm.dateRange = []
  filterForm.categoryIds = []
  handleSearch()
}

// 日期变化
const handleDateChange = () => {
  handleSearch()
}

// 分类变化
const handleCategoryChange = () => {
  handleSearch()
}

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 监听图表类型变化
watch(salesChartType, () => {
  fetchSalesTrend()
})

watch(hotGoodsType, () => {
  fetchHotGoods()
})

// 初始化
onMounted(async () => {
  await fetchCategories()
  initCharts()
  handleSearch()
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  salesChart?.dispose()
  categoryChart?.dispose()
  reviewChart?.dispose()
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.data-card {
  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  
  .card-content {
    text-align: center;
    
    .amount {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 8px;
    }
    
    .trend {
      font-size: 14px;
      
      .trend-value {
        &.up {
          color: #67c23a;
        }
        
        &.down {
          color: #f56c6c;
        }
      }
      
      .trend-label {
        color: #909399;
        margin-left: 4px;
      }
    }
  }
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .chart-container {
    height: 400px;
  }
}

.goods-info {
  display: flex;
  align-items: center;
  gap: 12px;
  
  .goods-image {
    width: 50px;
    height: 50px;
    border-radius: 4px;
  }
  
  .goods-detail {
    .goods-name {
      font-size: 14px;
      color: #303133;
      margin-bottom: 4px;
    }
    
    .goods-category {
      font-size: 12px;
      color: #909399;
    }
  }
}

.review-analysis {
  .review-overview {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    
    .review-score {
      text-align: center;
      
      .score {
        font-size: 36px;
        font-weight: bold;
        color: #ff9900;
        margin-bottom: 4px;
      }
      
      .score-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }
    }
    
    .review-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      max-width: 400px;
      
      .review-tag {
        margin-right: 8px;
        margin-bottom: 8px;
      }
    }
  }
  
  .review-trend {
    .trend-title {
      font-size: 14px;
      color: #303133;
      margin-bottom: 16px;
    }
  }
}

/* 响应式布局优化 */
@media screen and (max-width: 1400px) {
  .el-col-6 {
    width: 50%;
  }
  
  .el-col-8 {
    width: 100%;
  }
  
  .el-col-12 {
    width: 100%;
  }
  
  .el-col-16 {
    width: 100%;
  }
}

@media screen and (max-width: 768px) {
  .el-col-6 {
    width: 100%;
  }
  
  .review-analysis {
    .review-overview {
      flex-direction: column;
      align-items: center;
      gap: 16px;
      
      .review-tags {
        justify-content: center;
      }
    }
  }
}
</style> 